package com.feifan.consumer.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.face.AipFace;
import com.feifan.api.annotation.LogType;
import com.feifan.api.annotation.SystemLog;
import com.feifan.api.annotation.UserLoginToken;
import com.feifan.api.dto.AIBaiduFaceBean;
import com.feifan.api.dto.AIFaceBean;
import com.feifan.api.dto.UmsAdminLoginParam;
import com.feifan.api.model.UmsAdmin;
import com.feifan.api.service.ITokenService;
import com.feifan.api.service.IUserService;
import com.feifan.common.AIFactoryUtil;
import com.feifan.common.CommonResult;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: FinalProject
 * @author: Xiaofan
 * @createTime: 2021-08-03 09:23
 * @description: Functions of this class is
 **/
@RestController
@CrossOrigin//防止跨域问题
@RequestMapping({"/admin"})
@Api(tags = "UserController",value = "后台项目管理")//用于做文档展示给前端看
public class UserController {

    private AipFace aipFace=AIFactoryUtil.getAipFace();

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    //dobbo做法
    @Reference(
            version = "1.0.0",
            interfaceName = "com.feifan.api.service.IUserService",
            interfaceClass = IUserService.class,
            timeout = 170000
            //这个timeout时间一定要设置的长一点，不然当连接不上了就直接报错了！！！
    )
    private IUserService service;

    //dobbo做法
    @Reference(
            version = "1.0.0",
            interfaceName = "com.feifan.api.service.ITokenService",
            interfaceClass = ITokenService.class,
            timeout = 170000//防止一下子找不到zookeeper就连接中断
    )
    private ITokenService tokenService;

    @PostMapping(value = "/login")
    @ResponseBody
    @ApiOperation(value = "密码登录后返回token")
    @UserLoginToken(required = true)
    public CommonResult Login(@RequestBody UmsAdminLoginParam user) {
        UmsAdmin admin = service.findByUsername(user.getUsername());
        if (admin == null) {
            return CommonResult.validateFailed("用户不存在!");//说明用户不存在
        } else if (!user.getPassword().equals(admin.getPassword())) {
            //说明密码不对
            HashMap<String, String> transportMap = new HashMap<>();
            transportMap.put("error password!", "401");//用一个键值对集合，将错误信息与代码链接在一起，利于前端调试
            return CommonResult.failed(transportMap);
        } else {
            //当前登录用户为注册用户
            System.out.println("fuck!");

            //做一个token，防止有人通过一些暴力破解的方式来去破解账号密码
            String token = tokenService.getToken(admin.getId().toString(), admin.getPassword());
            HashMap<String, String> transportMap = new HashMap<>();
            transportMap.put("token",token);
            transportMap.put("success", "500");
            transportMap.put("tokenHead", tokenHead);
            return CommonResult.success(transportMap);//返回成功的
        }
    }
    @PostMapping(value = "/flogin")
    @ResponseBody
    @ApiOperation(value = "人脸登录后返回token")
    @UserLoginToken(required = true)
    public CommonResult faceLogin(@RequestBody AIFaceBean faceBean) {
        Map<String,String> transportMap=new HashMap<>();
       JSONObject jsonObject= aipFace.search(faceBean.getImgdata(),"BASE64","login",null);

        //依据类AIBaiduFaceBean中的对象  把jsonObject转换
        AIBaiduFaceBean aiBaiduFaceBean=JSON.parseObject(jsonObject.toString(), AIBaiduFaceBean.class);

        //开始判断
        if(aiBaiduFaceBean.getError_code().equals("0")&&aiBaiduFaceBean.getError_msg().equals("SUCCESS")){
            //说明脸部识别正确
            if(aiBaiduFaceBean.getResult().getUser_list().get(0).getScore()>80){
                //如果脸部对比度与库中脸谱识别率大于80，则证明当前用户存在
                faceBean.setError_code(aiBaiduFaceBean.getError_code());
                faceBean.setError_msg(aiBaiduFaceBean.getError_msg());
                String userId=aiBaiduFaceBean.getResult().getUser_list().get(0).getUser_id();//取出图片的名称

                UmsAdmin admin=service.findByUserId(userId);//通过图片名称ID号取出该用户信息
                String username=admin.getUsername();
                String password=admin.getPassword();
                String token=tokenService.getToken(userId,password);

                transportMap.put("error_code",aiBaiduFaceBean.getError_code());
                transportMap.put("token",token);
                transportMap.put("tokenHead",tokenHead);
                transportMap.put("username",username);
                transportMap.put("password",password);

                return CommonResult.success(transportMap);
            }
            else {
                transportMap.put("error_code",aiBaiduFaceBean.getError_code());
                return CommonResult.failed(transportMap);

            }
        }
        return CommonResult.success(aiBaiduFaceBean);
    }
    @GetMapping(value = "/info")
    @ResponseBody
    @ApiOperation(value = "获取当前登录用户信息")
    @SystemLog(description = "获取当前登录用户的信息",type = LogType.USER_INFO)
    @UserLoginToken(required = true)
    public CommonResult getAdminInfo(HttpServletRequest request){
        //取得从前端来的token码
        String token=request.getHeader(tokenHeader);//Bearer@XXX
        String tokenM=token.split("@")[1];//取出纯的token码

        UmsAdmin admin=service.findByToken(tokenM);//通过token找到该用户信息
        HashMap<String,Object> transportMap=new HashMap<>();
        transportMap.put("username",admin.getUsername());
        transportMap.put("roles",new String[]{"TEST"});
        transportMap.put("icon",admin.getIcon());
        return CommonResult.success(transportMap);
    }

    @PostMapping(value = "/logout")
    @ResponseBody
    @ApiOperation(value = "退出登录")
    @UserLoginToken(required = true)
    @SystemLog(description = "登出",type = LogType.USER_LOGIN_OUT)
    public CommonResult logout(){
        return CommonResult.success(null);
    }


    @PostMapping(value = "/reg")
    @ResponseBody
    @ApiOperation(value = "用户注册")
    @UserLoginToken(required = true)
    public CommonResult register(UmsAdmin umsAdmin){
        if(service.findByUsername(umsAdmin.getUsername())!=null){//说明该用户名已经被注册了
            Map<String,String> transportMap=new HashMap<>();
            transportMap.put("error_code","400");//返回一个错误码
            return CommonResult.failed(transportMap);
        }
        //说明没有被注册
        UmsAdmin admin=service.register(umsAdmin);//把新用户注册进去，并且返回一个新的用户对象
        //然后操作百度，进行人脸识别
        HashMap<String,String> tobaiduMap=new HashMap<>();
        tobaiduMap.put("user_info",admin.getPassword());
        String b64=umsAdmin.getPic().substring(22);//表示人脸识别中的图像识别码，后22位为图像的数据
        JSONObject jsonObject=aipFace.addUser(b64,"BASE64","login",umsAdmin.getId().toString(),tobaiduMap);

        Map<String,String> transportMap=new HashMap<>();
        transportMap.put("error_code","500");
        return CommonResult.success(transportMap);
    }

}